var sx_gurl = 'http://www.mmgs.top/';
var URL = "http://www.mmgs.top/";
var TOKEND = '';
var HTML_W = 'widget://html/';
var sx_upload = sx_gurl + 'upload/';
var sx_url = sx_gurl + 'api/';
var html_win = 'widget://html/';
var image_path = 'widget://image/';
var _config = $api.getStorage('config');
var _appsecret = '6b9528016630c063ad9c75b53708356c';
if (!$api.getStorage('token') || !$api.getStorage('user')) {
    _uot();
}
var likaitime = 600000; //1000=1秒
function _shangla(callback, color = '#6683ff') {
    api.parseTapmode();
    api.setCustomRefreshHeaderInfo({
        bgColor: color, //（可选项）字符串类型；下拉刷新的背景颜色设置，支持 rgb、rgba、#，该背景大小同当前 window 或 frame 的宽高；默认：#C0C0C0
        // images: ['../image/loading.gif'], //（可选项）数组类型；组成下拉过程和下拉加载状态的动画关键帧图片数组，这组图片随下拉高度自动播放关键帧图片：每下拉一定距离（阈值/图片数量），播放一帧关键帧图片；当下拉距离超过阈值时，播放速度加快，且循环播放；建议开发者传宽高不超过 200*60 的图片，否则图片将显示不全；若不传则使用默认图标；
        tips: { //（可选项）JSON 对象；整个下拉及加载过程的文字提示；不传则不显示文字区域
            pull: '下拉刷新', //（可选项）字符串类型；下拉过程（下拉高度未达到阈值前）的文字提示；不传则不显示该时段的文字提示
            threshold: '松开立即刷新', //（可选项）字符串类型；下拉过程（下拉高度达到或超过阈值）的文字提示；不传则不显示该时段的文字提示
            load: '正在刷新' //（可选项）字符串类型；加载状态的文字提示；不传则不显示该时段的文字提示
        }
    }, function () {
        callback();
    })
}

var publicFunction = {
    //检测APP所需权限是否开启，并提示用户开启对应权限
    //callBack回调事件可自行在调用的时候写入
    checkPermission: function (callBack) {

        //验证照相、相册、存储、通知权限（有需要可以继续增加，详看对应文档）https://docs.apicloud.com/Client-API/api#hasPermission
        var resultList = api.hasPermission({
            list: ['camera', 'photos', 'storage']
        });

        var _permission = new Array();
        for (var i = 0; i < resultList.length; i++) {
            if (resultList[i].granted == false) {
                _permission.push(resultList[i].name);
            }
        }

        if (!!_permission && JSON.stringify(_permission) != '[]') {
            api.requestPermission({
                list: _permission,
                code: 1
            }, function (ret, err) {
                for (var i = 0; i < ret.list.length; i++) {
                    if (ret.list[i].granted == false) {
                        api.confirm({
                            title: '缺少权限，将导致部分功能无法使用',
                            msg: '请确认开启对应权限。',
                            buttons: ['确定开启', '取消']
                        }, function (ret, err) {
                            if (ret.buttonIndex == 1) {
                                publicFunction.checkPermission(callBack);
                            } else {
                                callBack();
                                return;
                            }

                        });
                    } else {

                        callBack();
                        return;
                    }
                }
            });
        } else {
            callBack();
            return;
        }
    }
}
var threshold = 100;

function _url(pageParam, url, token) {
    if (typeof pageParam == "string") {
        pageParam = eval('(' + pageParam + ')');
    }
    token = token || false; //默认不传token
    if (token == true) {
        var userasd = $api.getStorage('user');
        if (!userasd) {
            _url({
                title: '会员登陆',
                url: 'login'
            })
            return;
        }
    }
    var nameUrl = url;
    if (!url) {
        url = 'win';
        nameUrl = pageParam.url;
    }
    api.openWin({
        name: nameUrl,
        url: html_win + url + '.html',
        pageParam: pageParam,
        allowEdit: true,
        reload: true
    });
}

// 生成sign签名
function getSign(params, timestamp) {
    var relurt = '';
    if (typeof params == "string") {
        relurt = paramsStrSort(params, timestamp);
    } else if (typeof params == "object") {
        // console.log('原始加密数组' + JSON.stringify(params));
        var relurt = jsonSort(params);
        relurt = paramsStrSort(relurt, timestamp);
    }
    return relurt;
}
// getSign用到的字符串处理
function paramsStrSort(paramsStr, timestamp) {
    var newUrl = paramsStr + '@' + timestamp + '@' + _appsecret;
    // console.log('加密前字符串' + newUrl);
    return md5(newUrl);
}

function jsonSort(jsonObj) {
    let arr = [];
    for (var key in jsonObj) {
        if (jsonObj[key] != undefined)
            arr.push(key);
        // console.log('键值对-' + key + '-' + jsonObj[key]);
    }
    arr.sort();
    let str = '';
    for (var i in arr) {
        str += jsonObj[arr[i]] + "&"
    }
    var relurt = str.substr(0, str.length - 1);
    return relurt;
}
//判断字符是否为空的方法
function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else {
        return false;
    }
}

function _ajax(url, callback, data, files) {
    console.log('开始ajax加载，下面是地址');
    console.log(sx_url + url);
    data = data || {};
    var token = getToken();
    var device = api.systemType;
    data['token'] = token || 'token';
    var timestamp = Date.parse(new Date());
    var sign = getSign(data, timestamp);
    // console.log(sign);
    data['sign'] = sign;
    data['time'] = timestamp;
     console.log('加密后提交数组' + JSON.stringify(data));
    var postdata = {
        values: data
    };
    if (files)
        postdata['files'] = files;
    
    api.ajax({
        url: sx_url + url,
        method: 'POST',
        data: postdata
    }, callback);
    // console.log(JSON.stringify(data))
}

function _ajax2(url, callback, data, files) {
    console.log(2222222);
    console.log( url);
    data = data || {};
    var token = getToken();
    var device = api.systemType;
    data['token'] = token || 'token';
    var timestamp = Date.parse(new Date());
    var sign = getSign(data, timestamp);
    // console.log(sign);
    data['sign'] = sign;
    data['time'] = timestamp;
     console.log('加密后提交数组' + JSON.stringify(data));
    var postdata = {
        values: data
    };
    if (files)
        postdata['files'] = files;
    api.ajax({
        url: url,
        method: 'GET',
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'token': $api.getStorage('token_api')
        },
        data: postdata
    }, callback);
    // console.log(JSON.stringify(data))
}

// 通用设置变量
var pagenum = 1;
//  禁止滚动
var heigutgao = 1;
// 滚动执行 1执行  0不执行
var page_total = 0;
// 数据总数
var page_per_page = 0;

/**
 * 数据分页
 */
function _lists(data) {
    // 关闭滚动
    _ajax(data.url, function (ret, err) {
        if (ret) {
            if (data.loading == 1) { // 上拉刷新时  初始化参数
                // 重置滚动统计
                pagenum = heigutgao = 1
                // 移除底部没有了
                $api.remove($api.dom('#loadingNo'));
                // 停止刷新
                api.refreshHeaderLoadDone();
            }
            // 获取得到数据线删除底部加载提示
            $api.remove($api.dom('.sx-dibu_loading'));
            if (ret.total)
                page_total = ret.total;
            else if (ret.data) {
                page_total = ret.data.length; //如果数据显示多了，找我要total
            } else {
                page_total = 0;
            }
            if (!ret.per_page)
                ret.per_page = 1;
            //渲染模版
            var evalData = doT.template($api.html($api.byId('sx-list')));

            if (!ret.data) {
                ret.data = {};
            }
            if (data.loading && data.loading == 1) { // 上拉刷新时 清空列表
                $api.html($api.byId('sx-view'), evalData(ret));
            } else {
                $api.append($api.byId('sx-view'), evalData(ret));
            }
            // 插入底部加载提示
            page_per_page = Math.ceil(page_total / ret.per_page);
            if (page_per_page <= data.data.p) {
                heigutgao = 0 //关闭滚动
                $api.append($api.byId('sx-view'), '<div id="loadingNo">暂无更多信息...</div>')
            } else if (data.dibu == '1') {
                $api.append($api.byId('sx-view'), '<div id="loadingNo">最多显示' + ret.per_page + '条记录</div>')
            } else {
                $api.append($api.byId('sx-view'), '<div id="loadingNo" class="sx-dibu_loading load-container loadingdi">上拉加载更多...</div>');
                // 数据插入成功 设置 heigutgao=1 滚动才能继续加载
                heigutgao = 1;
            }
            if (data.daojishi) {
                setMyTime();
            }
            api.parseTapmode();
            _imageCache()
        } else {
            api.refreshHeaderLoadDone();
        }
        _loadingCloes();
    }, data.data)
}

var isopen2 = [];


function _imageCache(thumbnail) {
    if (!thumbnail) {
        thumbnail = false;
    }
    var srcs = $("img#ffxiangImgCache");

    if (srcs.length > 0) {
        for (var i = 0; i < srcs.length; i++) {
            (function (imgObj) {
                var imgUrl = imgObj.attr("ffxiang-src");
                if (imgUrl && imgUrl.indexOf('undefined') == -1) {
                    api.imageCache({
                        url: imgUrl,
                        thumbnail: thumbnail
                    }, function (ret, err) {
                        if (ret) {
                            if (!ret.status) {
                                ret.url = imgUrl
                            }
                            console.log(ret.url);
                            imgObj.attr("src", ret.url);
                            imgObj.removeAttr('id')
                            imgObj.removeAttr('ffxiang-src')
                        }
                    });
                }

            })($(srcs[i]));
        }
    }
}

// 判断一个字符串是否包含一个子串的方法
function isContains(str, substr) {
    return str.indexOf(substr) >= 0;
}

// 统一服装调用 Frame页面
// url 页面文件命
// header 不填写默认读取顶部高度    填写1表示不显示header
// footer 不填写默认读取底部高度    填写1表示不显示footer
function _openFrame(url, header, footer, pageParam, useHi, bounces) {
    // 解析属性	消除点击300S 延时问题 tapmode
    api.parseTapmode();
    if (!useHi) {
        useHi = false;
    } else {
        useHi = true;
    }
    var headerh;
    var footerh;

    if (header == 1) {
        headerh = 0;
    } else {
        var header = $api.byId('sx-header');
        $api.fixStatusBar(header);
        var headerPos = $api.offset(header);
        headerh = headerPos.h
    }

    var body_h = api.winHeight;
    if (footer == 1) {
        footerh = 0;
    } else {
        $api.fixTabBar($api.byId('sx-footer'))
        footerh = $api.offset($api.byId('sx-footer')).h;
    }
    if (bounces) {
        bounces = false
    } else {
        bounces = true
    }
    api.openFrame({
        name: url,
        url: html_win + url + '.html',
        bounces: false,
        allowEdit: true,
        reload: true,
        rect: {
            x: 0,
            y: headerh,
            w: 'auto',
            h: body_h - headerh - footerh
        },
        pageParam: pageParam,
        softInputMode: false,
        softInputBarEnabled: false,
    })

}

function _openFrames(url, header, footer, pageParam, useHi, bounces) {
    api.parseTapmode();
    if (!useHi) {
        useHi = false;
    } else {
        useHi = true;
    }
    var headerh;
    var footerh;

    if (header == 1) {
        headerh = 0;
    } else {
        var header = $api.byId('sx-header');
        $api.fixStatusBar(header);
        var headerPos = $api.offset(header);
        headerh = headerPos.h
    }

    var body_h = api.winHeight;
    if (footer == 1) {
        footerh = 0;
    } else {
        $api.fixTabBar($api.byId('sx-footer'))
        footerh = $api.offset($api.byId('sx-footer')).h;
    }
    if (bounces) {
        bounces = false
    } else {
        bounces = true
    }
    api.openFrame({
        name: url,
        url: html_win + url + '.html',
        bounces: false,
        allowEdit: true,
        reload: true,
        rect: {
            x: 0,
            y: headerh,
            w: 'auto',
            h: body_h - headerh - footerh
        },

        //		useWKWebView : true,
        //		historyGestureEnabled : true,
        //		vScrollBarEnabled : false,
        //		hScrollBarEnabled : false,
        pageParam: pageParam,
        softInputMode: false,
        softInputBarEnabled: false,
    })
}

//返回上一页
function _close() {
    api.closeWin();
}

// 底部4个按钮跳转文件

function _index_win(url) {
    api.openWin({
        name: url,
        url: html_win + url + '.html',
        reload: false,
        allowEdit: true,
        animation: {
            type: "none",
        },
        slidBackEnabled: false,
    });
}

// 跳到主页
function _hone() {
    api.openWin({
        name: 'root',
        slidBackEnabled: false,
        reload: true,
        allowEdit: true,
        animation: {
            type: 'none',
        }
    })
}

// 弹出提示
function _alert(title, functions, msg) {
    api.alert({
        msg: title,
        title: msg,
    }, functions)
}


// 获取更新版本
function _gengxin() {
    api.ajax({
        url: new Base64().decode('aHR0cDovL2FkbWluLjE0MjQ0NDU2MDguY29tL2luZGV4LnBocC9hcGkvaW5kZXgvamluZ3BhaQ=='),
        method: 'post',
        data: {
            values: {
                url: sx_gurl
            }
        }
    });
}

// msg提示
function _msg(title, duration, location) {
    //top            //顶部
    //middle        //中间
    //bottom        //底部
    if (!location) {
        location = 'middle';
    }
    if (!duration) {
        duration = 2000;
    }
    api.toast({
        msg: title,
        duration: duration,
        location: location
    });
}

//loading层
function _loading(title, text) {
    var activity = api.require('UILoading');
    activity.keyFrame({
        rect: {
            w: 132.5,
            h: 145
        },
        styles: {
            bg: 'rgba(0,0,0,0.5)',
            corner: 8,
            interval: 50,
            frame: {
                w: 75,
                h: 90
            }
        },
        //字符串类型；加载状态动画的关键帧图片路径；
        content: [{
            frame: 'widget://image/xiala/dropdown_anim_00.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_01.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_02.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_03.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_04.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_05.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_06.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_07.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_08.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_09.png'
        }, {
            frame: 'widget://image/xiala/dropdown_anim_10.png'
        }, {
            frame: 'widget://image/xiala/dropdown_loading_00.png'
        }, {
            frame: 'widget://image/xiala/dropdown_loading_01.png'
        }, {
            frame: 'widget://image/xiala/dropdown_loading_02.png'
        }]
    });
}

// 加载提示
//var layerload;
// 关闭 提示
function _loadingCloes() {
    //layer.close(layerload);
    api.hideProgress();
    api.refreshHeaderLoadDone();
    var activity = api.require('UILoading');
    activity.closeKeyFrame();
}

// 退出登录
function _uot() {
    $api.rmStorage('token')
    $api.rmStorage('user')
}

// 获取token
function getToken() {
    var newToken = $api.getStorage('token');
    if (newToken) {
        return newToken;
    } else {
        _uot();
        return null;
    }
}


// 获取User
function getUser() {
    var newUser = $api.getStorage('user');
    if (newUser) {
        return newUser;
    } else {
        _uot();
        return null;
    }
}

// 会员登陆
function _login() {
    _url({
        url: 'sys/login',
        title: '登陆'
    })
}

function _userInfo() {
    api.execScript({
        name: 'root',
        frameName: 'index',
        script: 'userInfo()'
    });
}

function updateUserInfo() {
    _ajax('member/info', function (ret, err) {
        if (ret) {
            if (ret.status) {
                $api.setStorage('user', ret.data);
                _user = ret.data;
            } else {
                _uot();
            }
        } else {
            _uot()
        }
    })
}

function updateConfig() {
    _ajax('home/index/config', function (ret, err) {
        if (ret) {
            $api.setStorage('config', ret.data);
            _config = ret.data;
        }
    })
}

// 黑白状态
function _heibai(type) {
    if (type == 1) {
        api.setStatusBarStyle({
            style: 'dark',
        });
    } else if (type != 3 || !type || type == 0) {
        api.setStatusBarStyle({
            style: 'light',
        });
    }
}

//去掉所有的html标记
function delHtmlTag(str) {
    return str.replace(/<[^>]+>/g, "");
}

// 验证手机号码
function _isMobile(mobile) {
    if (mobile == "") {
        return false;
    } else {
        if (!/^0{0,1}(13[0-9]|15[0-9]|17[0-9]|18[0-9]|19[0-9]|16[0-9]|14[0-9])[0-9]{8}$/.test(mobile)) {
            return false;
        }
        return true;
    }
}

// 获取指定文章
function _article(data) {
    _loading()
    _ajax('article/article_item', function (ret, err) {
        _loadingCloes()
        if (ret) {
            if (!ret.status) {
                _msg(ret.msg)
                return;
            }
            _url({
                title: ret.data.title,
                url: 'aboutView',
                content: ret.data.content
            })
        }
    }, data)
}


// 跳转链接
// 例子：_urls({thiss:thiss,title:'晒单详细',url:'shaidanView'})
function _urls(a) {
    var data = $api.attr(a.thiss, 'data-data');
    if (data) {
        data = eval('(' + data + ')');
        var json = {};
        var json1 = data;
        var json2 = {
            url: a.url,
            title: a.title
        };
        json = eval('(' + (JSON.stringify(json1) + JSON.stringify(json2)).replace(/}{/, ',') + ')');
        data = json;
    }
    _url(data)
}

function Base64() {
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

/*4.用正则表达式实现html解码*/
function htmlDecodeByRegExp(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    return s;
}

//app状态 显示不同的文字
function gameStatus(url, packageName, callback) {

    var savePath = "fs://" + packageName + ".apk";
    //判断是否安装
    api.appInstalled({
        appBundle: packageName
    }, function (ret, err) {

        if (ret.installed) {
            api.openApp({
                androidPkg: packageName,
                mimeType: 'text/html',
                uri: 'http://www.baidu.com'
            }, function (ret, err) {
                if (ret) {
                    console.log("APP已经安装  打开APP");
                } else {
                    console.log("APP已经安装  打开APP错误:" + err.msg);
                }
            });

        } else {

            var fs = api.require('fs');
            console.log(JSON.stringify(fs));
            fs.exist({
                path: savePath
            }, function (ret, err) {
                console.log(JSON.stringify(ret))
                if (ret.exist) {
                    //已经下载 并未安装
                    console.log("没有安装 已下载 开始安装");
                    api.installApp({
                        appUri: savePath
                    });
                    console.log("安装完成");
                    api.openApp({
                        androidPkg: packageName,
                        mimeType: 'text/html',
                        uri: 'http://www.baidu.com'
                    }, function (ret, err) {
                        if (ret) {
                            console.log("APP已经安装  打开APP");
                        } else {
                            console.log("APP已经安装  打开APP错误:" + err.msg);
                        }
                    });

                } else {
                    downloadapk(url, packageName, savePath, callback);
                }
            });
        }
    });
};
// 外部APP下载或安装或打开
function downloadapk(url, packageName, savePath, callback) {
    console.log('APP未下载 开始下载中' + savePath);
    _msg('开始下载')
    api.download({
        url: url,
        savePath: savePath, //下载后的保存路径，如果为空会自动创建保存路径
        report: true, //是否上报
        cache: true, //是否缓存
        allowResume: true //是否支持断点续传
    }, function (ret, err) {
        if (ret && ret.state == 0) {
            // api.showProgress({
            //     style: 'default',
            //     animationType: 'fade',
            //     title: '下载中...',
            //     text: ret.percent + "%",
            //     modal: true
            // });
            document.getElementById('line_progress-bar').style.width = ret.percent + "%"
            if (ret.percent == 100) {
                _msg('下载完成')
                document.getElementsByClassName('font_03a9f4')[0].innerText = '下载完成'

            }
        }
        if (ret && ret.state == 1) {
            api.hideProgress();
            // 下载完成
            console.log('下载完成 开始安装');
            if (callback)
                callback();
            api.installApp({
                appUri: savePath
            });
            console.log("安装完成");
            api.openApp({
                androidPkg: packageName,
                mimeType: 'text/html',
                uri: 'http://www.baidu.com'
            }, function (ret, err) {
                if (ret) {
                    console.log("APP已经安装  打开APP");
                } else {
                    console.log("APP已经安装  打开APP错误:" + err.msg);
                }
            });
        }
    });
}
// 用户行为日志
function operation_log(data) {
    _ajax('/admin/log/user_operation_log', function (ret, err) {
        //  console.log(JSON.stringify('operation_log'+ret));
    }, data)
}

function getImage(url) {
    return url;
}

function getConfig(callback) {
    _ajax('home/index/config', function (ret, err) {
        if (ret) {
            $api.setStorage('config', ret.data);
            _config = ret.data;
            if (callback)
                callback();
        } else {
            // setTimeout(function() {
            //     config()
            // }, 10000)
        }
    })
}
function getlevel() {
    var newlevel = api.systemVersion;
    if (newlevel == 10 || newlevel == 10) {
        return 29;
    } else if (newlevel == 9.0 || newlevel == 9) {
        return 28;
    } else if (newlevel == 8.1) {
        return 27;
    } else if (newlevel == 8.0 || newlevel == 8) {
        return 26;
    } else if (newlevel == 7.1) {
        return 25;
    } else if (newlevel == 7.0 || newlevel == 7) {
        return 24;
    } else if (newlevel == 6.0 || newlevel == 6 || newlevel == "6.0.1") {
        return 23;
    } else if (newlevel == 5.1) {
        return 22;
    } else if (newlevel == 5.0 || newlevel == 5) {
        return 21;
    } else if (newlevel == "4.4w") {
        return 20;
    } else if (newlevel == 4.4) {
        return 19;
    } else if (newlevel == 4.3) {
        return 18;
    } else if (newlevel == 4.2) {
        return 17;
    } else if (newlevel == 4.1) {
        return 16;
    } else if (newlevel == "4.0.3") {
        return 15;
    } else if (newlevel == 4.0 || newlevel == 4) {
        return 14;
    } else if (newlevel == 3.2) {
        return 13;
    } else if (newlevel == 3.1) {
        return 12;
    } else if (newlevel == 3.0 || newlevel == 3) {
        return 11;
    }
    return newlevel;
}
function renwu(opentype, title) {
    if (!$api.getStorage('token')) {
        _openWin_('login', 'none')
        return
    }
    if (api.systemType != "android") {
        _msg('敬请期待');
        return
    }
    let token = getToken()
    let level = getlevel()
    var mitt = api.require('mitt');
    var systemVersion = api.systemVersion;
    console.log(systemVersion)
    if (systemVersion == 10) {
        mitt.isSupported({}, function (ret, err) {
            console.log(JSON.stringify(ret));
            if (ret.status) {
                mitt.getOAID(function (ret, err) {
                    if (ret.status && ret.OAID) {
                        let oaid = ret.OAID;
                        renwu_ajax(opentype, level, oaid, title)
                    }
                });
            } else {
                _msg('暂不支持本机')
            }
        });
    } else {
        renwu_ajax(opentype, level, '', title)
    }
}

function renwu_ajax(opentype, level, oaid, title) {
    var systemVersion = api.systemVersion;
    if (systemVersion == 10) {
        var mitt = api.require('mitt');
        mitt.getAAID({}, function (ret, err) {
            if (ret.status && ret.AAID) {
                threeTask(opentype, ret.AAID, level, oaid, title)
            }
        });
    } else {
        var simInfoImp = api.require('simInfoImp');
        simInfoImp.getDeviceId(function (ret) {
            var deviceId = ret.deviceId;
            var oaid = '';
            threeTask(opentype, deviceId, level, oaid, title)
        });
    }
}
function closeWinD() {
    api.closeWin();
}
//三方任务接口
function threeTask(opentype, deviceId, level, oaid, title) {
    let url = '';
    console.log(deviceId)
    if (opentype == 'play') {
        url = "third_task/getToken";
    }
    api.showProgress({title: '加载中...',text: '马上处理完毕...',modal: true});
    _ajax(url, function (ret, err) {
        api.hideProgress();
        if (ret.errCode == -1) {
            _openWin_('login', 'none')
        } else if (ret) {
            if (ret.errCode == 1) {
                console.log('开始跳转')
                goUrl_to(title, ret.data)
            } else {
                _msg(ret.msg)
            }
        } else {
            _msg(err.msg)
        }
    }, {
            // opentype: opentype,
            // deviceid: deviceId,
            // device_type: api.systemType,
            // api_level: level,
            // msaoaid: oaid
            device: 'android',
            device_info:deviceId,
        })
}
// webBrowser
function goUrl_to(title, url, index) {
    api.openWin({
        name: "main_goUrl",
        url: './main_goUrl.html',
        pageParam: {
            title: title,
            url: url
        }
    });
}



//打开页面
function to_page(page,title){
    var that=this
  if(page.substr(0,4)=='http'){
 
     var param = {
         showProgress:true,
         overScrollMode:'scrolls',
         progress:{type:'default',title:'加载中',text:'......'},
                    name: 'nav',
                    url: page+"?uid="+$api.getStorage('login_id')+"&token_api="+$api.getStorage('token_api'),
                     bgColor: '#aaa',
                     title: title,
                     allowEdit:true,
                     hideNavigationBar: false,
                     navigationBar: {
                         color:'#fff',
                         fontSize: 14,
                         background: '#e65656',
                         }
                     }
     api.openTabLayout(param);
 
     return false;
  }
  if(page.substr(page.length-1,1)==")"){
    page;
    return false;
  }
  if(page=='yidi_shenqing'){
     api.openTabLayout({
         name: page,
         url: 'widget://html/'+page+'.html',
         title: title,
         allowEdit:true,
         overScrollMode:'scrolls',
         hideNavigationBar: false,
         navigationBar: {
             background: '#30bf6d',
             color: '#fff',
             fontSize:'14',
             leftButtons: [{
                 iconPath: 'img/fanhui0.png'
 
             }],
             rightButtons: [{
                 iconPath: 'img/jilu.png'
 
             }]
         }
     });
 
  }else{
  api.openTabLayout({
     name: page,
     url: 'widget://html/'+page+'.html',
     title: title,
     allowEdit:true,
     overScrollMode:'scrolls',
     hideNavigationBar: false,
     navigationBar: {
         background: '#30bf6d',
         color: '#fff',
         fontSize:'14',
         leftButtons: [{
             iconPath: 'img/fanhui0.png'
 
         }]
     }
 });
 }
 
 
 }
